<template>
  <view class="login-no-token">
    <uni-icons type="contact-filled" size="100"></uni-icons>
    <button type="primary" class="login-btn" @click="getUserInfo">立即登录</button>
    <text>登录享受更多权限</text>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import badgeMix from '@/mixins/tabbar-badge.js'
  export default {
    methods: {
      ...mapMutations('modulesUser', ['updateUserInfo', 'updateToken','updateRedirectInfo']),
      // 获取用户信息
      getUserInfo() {
        // 获取登录授权
        uni.getUserProfile({
          desc: '需要授权登录',
          lang: 'zh_CN',
          success: (e) => {
            this.updateUserInfo(e.userInfo)
            this.getToken(e)
            uni.$showMsg('登录成功')
          },
          fail: () => {
            uni.$showMsg('登录失败')
          },
        })
      },
      // 获取 token 登录凭证
      async getToken(info) {
        // 调用微信登录接口
        const [err, res] = await uni.login({
          onlyAuthorize: true,
        }).catch(err => err)
        // 判断是否 uni.login() 调用失败
        if (err || res.errMsg !== 'login:ok') return uni.$showError('登录失败！')

        // 准备参数对象
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }

        const {
          data: loginResult
        } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
        // 接口对 code 判断有问题,这里走一个流程
        // if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')

        // token 无效,直接用假的
        const newToken =
          "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo"
        uni.$showMsg('登录成功')
        this.updateToken(newToken)
        // 可能是需要跳转到购物车的时候
        if (this.redirectInfo) {
          uni.switchTab({
            // 要导航到的页面地址
            url: this.redirectInfo.from,
            // 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      }
    },
    computed: {
      ...mapState('modulesUser', ['token', 'userInfo', 'redirectInfo'])
    },
    mixins: [badgeMix]
  }
</script>

<style lang="less">
  .login-no-token {
    height: 400rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
    font-size: 13px;
    color: gray;

    .login-btn {
      width: 90%;
      border-radius: 100px;
    }
  }
</style>
